# coding:utf-8
from appium import webdriver
import os
import yaml


class DriverConfig:
    """将driver实例的生成进行了封装"""

    def __init__(self):
        self.dir = os.path.dirname(os.path.realpath(__file__))  # 当前目录
        self.project_dir = os.path.abspath('..')  # 项目目录

    def replace_dir(self, path):
        """将相对路径转换为绝对路径"""
        if os.path.exists(path):
            return
        path = os.path.join(self.project_dir, path)
        return path

    def get_desired_caps(self, devicename):
        """读取yaml文件中的设备信息"""
        path = os.path.join(self.dir, "desired_caps.yaml")
        with open(path) as f:
            devices_info = yaml.load(f)
        # 根据设备名确定端口与配置信息
        for device in devices_info:
            if device["deviceName"] == devicename:
                # 替换相对路径为绝对路径
                if "chromedriverChromeMappingFile" in device["desired_caps"]:
                    device["desired_caps"]["chromedriverChromeMappingFile"] = self.replace_dir(device["desired_caps"]["chromedriverChromeMappingFile"])
                    device["desired_caps"]["chromedriverExecutableDir"]= self.replace_dir(device["desired_caps"]["chromedriverExecutableDir"])
                return device

    def print_device_info(self, device):
        print("==============设备信息================")
        print("设备名称：" + device["deviceName"])
        print("端口：" + str(device["port"]))
        for k in device["desired_caps"]:
            print(k + ":" + str(device["desired_caps"][k]))
        print("=====================================\n")

    def get_driver(self, deviceinfo):
        """根据设备信息，生成driver的实例"""
        port = deviceinfo["port"]
        desired_caps = deviceinfo["desired_caps"]
        url = "http://localhost:%s/wd/hub" %port
        driver = webdriver.Remote(url, desired_caps)
        driver.implicitly_wait(10)
        return driver

